function mainInit(){
	
	//Resize main container
	var h = $(window).height() - $('header').height() - $('footer').height();
	$('#splitterWrapper').height(h);
	
	mainPanel.init();
	//sliderController depende de stateController
	stateController.init();
	//leftTree.init();
	//mainCanvas.init();
	imageSource.init();
	sliderController.init();
	sceneList.init();
	//actionController depende de stateController
	timeline.init();
	actionController.init();
	textController.init();
	previewController.init();
	settings.init();
	batchNodeController.init();
	
	//Header menu
	$("#menu").kendoMenu();
	
	//Book title & scene title
	$('#book-name-input, #scene-name-input')
		.blur(function(e){
			
			var name = $.trim($(this).val());
			if (name == ""){
				$(this).focus();
				return
			}
			
			if ($(this).attr('id') == 'scene-name-input'){
				sceneList.selected().item.attr('sceneName', name);
			}
		})
		.keyup(function(keyEvent){
			
			keyEvent = keyEvent? keyEvent : window.event;
			var keyCode = (keyEvent.keyCode ? keyEvent.keyCode : keyEvent.which);
			
            if ( keyCode == 13){ 
				$(this).blur();
            }
		})
		
		
	//new book button
	$('#newBookBtn').click(function(){
		var r=window.confirm("¿Estás seguro de que quieres comenzar un nuevo libro? Perderás los cambios que no hayas guardado en el actual.");
		if (r) {
			document.location.reload();
		}
	})
	
	
	//export button
	$('#exportBtn').click(function(){
		
		if (_checkNames()){
			
			$('#export-msg').empty().removeClass('ok-msg');
			//$('#export-file-name').val($('#book-name-input').val());
			$("#export-window").data("kendoWindow").center().open();	
			_exportBook();
		}
		
	});
	
	
	//Open book button
	$('#openBookBtn').click(function(){

		$('#error-msg').empty();
		$("#import-window").data("kendoWindow").center().open();
	});
	
	
	//Upload image button
	$('#uploadImagesLocalButton').click(function(){

		if($("#files").data("kendoUpload")){
			$("#upload-window div").html('<input name="files" id="files" type="file" />');
		}

		$("#files").kendoUpload({
        	async: {
                saveUrl: "/upload",
                autoUpload: true
            },
            multiple: false,
            showFileList: true,
            success: _onUploadImageSuccess,
            error: _onUploadImageError,
            select: _onSelect,
            localization: {
            	select: "Seleccionar"
            }
        });
		
		function _onSelect(){
			
			$('#upload-msg').text('Cargando imagen...');
		}
		
		function _onUploadImageError(e){
			
			console.log('Upload image error', e);	
			_onUploadImageComplete(e);
		}
		function _onUploadImageSuccess(e){
			
			console.log('Upload image success', e);	
			_onUploadImageComplete(e);
		}
		
		function _onUploadImageComplete(e){
			
			var extension = e.files[0].extension;
			var size = e.files[0].size;
			
			/*if (size > 1048576){
				
				$('#upload-msg').text('El tamaño máximo de la imagen es 1MB.');
			}
			else */
			if (extension != ".jpg" && extension != ".png" && extension != ".gif"){
		
				$('#upload-msg').text('La imagen seleccionada no es válida.');
			}
			else {
				
				var fileName = e.files[0].name;
				var newImage = {
					url:  "/getFile?fileName=" + fileName,
					title: fileName
				}

				var times = 0;
				function _checkImg(){
					
					var url = newImage.url
					
					$.get(url)
						.success(function(d){
							if (d){
								imageSource.dSource.add(newImage)
								imageSource.imageList.data('kendoListView').refresh();
								$("#upload-window").data("kendoWindow").close();
							}
							else {
								times++
								if (times < 10){
									window.console.log('Reintento carga de imagen')
									window.setTimeout(_checkImg, 3000);	
								}
								else {
									window.alert('Lo sentimos. Se ha producido un error cargando la imagen.')
								}
							}
						})
						.error(function(){
							
							times++
							if (times < 10){
								window.console.log('Reintento carga de imagen')
								window.setTimeout(_checkImg, 3000);	
							}
							else {
								window.alert('Lo sentimos. Se ha producido un error cargando la imagen.')
							}
							
						})
				}
				
				
				_checkImg()
				
			}
		}
		
		$('#upload-msg').text('');
		$("#upload-window").data("kendoWindow").center().open();
	});

	
	_initImportWindow();
	_initExportWindow();
	_initUploadWindow();
	_initShowTimelineWindow();
	
	function _initShowTimelineWindow(){
		
		var timelineWindow = $("#timeline-window");
		
		timelineWindow.kendoWindow({
			  width: "750px"
			, height: "382px"
			, title: "Timeline"
			, modal: true
			, visible: false
			, draggable: false
			, resizable: false
		});
	}
	
	//Init import window
	function _initImportWindow(){
		
		var importWindow = $("#import-window");
		var errorMsg = $('#error-msg');
		
		importWindow.kendoWindow({
			  width: "600px"
			, height: "175px"
			, title: "Abrir libro"
			, modal: true
			, visible: false
			, draggable: false
			, resizable: false
		});
		
		//Book upload button		
		$("#import-book-button").kendoUpload({
        	async: {
                saveUrl: "/upload",
                autoUpload: true
            },
            showFileList: false,
            success: _onUploadSuccess,
            error: _onUploadError,
            localization: {
            	select: "Seleccionar"
            }
		});
		
		
		function _onUploadError(e){
		
			console.log('Upload error', e);	
			var times = 0;
			_onUploadComplete(e, times);
		}
		
		function _onUploadSuccess(e){
			
			console.log('Upload success', e);	
			var times = 0;
			_onUploadComplete(e, times);
		}
		
		//Comprobación de que el libro ya está disponible en el datastore
		//Se lanzan 10 reintentos como máximo
		function _onUploadComplete(e, times){
			
			errorMsg.text('Cargando...')
			
			var extension = e.files[0].extension;
			if (extension == ".plist"){
				
				var fileName = e.files[0].name;
				$.ajax({
						  url: "/getFile?fileName=" + fileName
						, dataType: "xml"
						, success: function(data){
							
							console.log('Data: ', data)
							var book = $.plist(data);
							console.log('Book loaded: ', book);
							
							errorMsg.empty();
						
							if (openBook(book)){
								errorMsg.empty();
								$("#import-window").data("kendoWindow").close();
							}
							else {
								errorMsg.text('Error. El fichero no tiene definido el atributo iOSDevice.')
							}
						}
						, error: function(){
							times++
							if (times < 10){
								window.console.log('Get '+ fileName + '. Time: ' + times)
								window.setTimeout(
									function(){
										_onUploadComplete(e, times)
									}
									, 3000
								);
							}
							else {
								errorMsg.removeClass('ok-msg').text('Se ha producido un error en la operación.')
							}
						}
					})
			}
			else {
				errorMsg.text('La extensión del fichero seleccionado debe ser .plist');
			}
			
		}
		
	}//end _initImportWindow function
	
	
	//Init export window
	function _initExportWindow(){
		
		var wind = $("#export-window");
		wind.kendoWindow({
			  width: "600px"
			, height: "150px"
			, title: "Guardar libro"
			, modal: true
			, visible: false
			, draggable: false
			, resizable: false
		});
		
	}//end _initExportWindow function
	
	
	

	
	//Init upload window
	function _initUploadWindow(){
		
		var uploadWindow = $("#upload-window");
		uploadWindow.kendoWindow({
			  width: "600px"
			, height: "195px"
			, title: "Nueva imagen"
			, modal: true
			, visible: false
			, draggable: false
			, resizable: false
		});
		
	}//end _initExportWindow function
	
	
	//Export book
	function _exportBook(){
		
		var times = 0;
		var fileName = $('#export-file-name').val();
		var exportMsg = $('#export-msg');
		
		var book = saveBook();
		console.log(book);		
		
		if (book){
			
			exportMsg
			.addClass('ok-msg')
			.text('Espera unos segundos mientras se guarda el libro...');
			
			var plist = json2plist(book);
			
			var param = {
				plist: plist
			}
			
			$.post('/save?fileName=' + fileName, param, function(data) {
				
				_download();
			});
			
			//Comprobación de que el libro ya está disponible en el datastore
			//Se lanzan 10 reintentos como máximo
			function _download(){

				var url = '/download?fileName=' + fileName;
				
				$.get(url)
					.success(function(){
						location.href = url;
						exportMsg.addClass('ok-msg').text('¡Libro guardado con éxito!')
					})
					.error(function(){
						
						times++
						if (times < 10){
							window.setTimeout(_download, 3000);	
						}
						else {
							exportMsg.removeClass('ok-msg').text('Se ha producido un error en la operación.')
						}
						
					})
			}
			
//			var uriContent = "data:application/octet-stream," + encodeURIComponent(plist);
//			location.href = uriContent
			
//			var bb = new BlobBuilder;
//			bb.append(plist);
//			saveAs(bb.getBlob("text/plain;charset=utf-8"), fileName + ".plist");
			
		}
		else {
			exportMsg.removeClass('ok-msg').text('Se ha producido un error en la operación.')
		}
		
	}
	
	
	/*
	 *  Comprobar que no haya nombres de escena duplicados
	 *  ni nombres de actor duplicados en la misma escena 
	 *  
	 */
	function _checkNames(){
		
		var   repeated = false
			, i = 0
			, j = 0
			, scenesLength = sceneList.scenes.length
			, actorNames = []
		;

		while (!repeated && i < scenesLength){
			
			//Comprobación de nombres de escena repetidos
			j = 0;
			while (!repeated && j < scenesLength){
				
				if(i != j && sceneList.scenes[i].item.attr('sceneName') == sceneList.scenes[j].item.attr('sceneName')){
					
					var sceneName =  sceneList.scenes[i].item.attr('sceneName');
					repeated = 'ERROR. Hay más de una escena con el título ' + sceneName;
				}
				else {
					j++
				}
				
			}
			
			//Comprobación de objetos por escena
			var leafs = [];
			var sceneName = sceneList.scenes[i].item.attr('sceneName');
			
			$.each(sceneList.scenes[i].tree.treeView.element.find('span.k-in'), function(i, e){
				var objectName = $(e).html();
				if (!objectName){
					repeated = 'ERROR. En la escena ' + sceneName + ' hay objetos sin nombre.';
				} else {
					leafs.push( $.trim($(e).html()));	
				}
				
			});
			
			j = 0;
			while (!repeated && j < leafs.length-1){
				
				if ($.inArray(leafs[j], leafs, j+1) != -1) {
					
					repeated = 'ERROR. En la escena ' + sceneName + ' hay nombres de objetos repetidos.';
				}
				j++;
			}
			
			i++;
			
		}
		
		if (repeated){
			alert(repeated);
			return false;
		}
		else {
			return true;
		}

	}
	
}